import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:nine_grid_view/nine_grid_view.dart';
import 'package:o2oa_all_platform/common/extension/index.dart';

import '../../../../common/models/index.dart';
import '../../../../common/utils/index.dart';
import '../../../../common/values/index.dart';
import '../../../../common/widgets/index.dart';
import '../controller.dart';

///
/// 会话列表
///
class ConversationListWidget extends GetView<ImController> {
  const ConversationListWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.all(10),
        child: Obx(() => RefreshIndicator(
            onRefresh: () => controller.loadConversationList(),
            child: Column(
              children: [
                Visibility(
                  visible: controller.state.showInstantMsg,
                  child: lastInstantMsgItemView(context)
                ),
                Visibility(
                  visible: controller.state.showInstantMsg,
                  child: const SizedBox(height: 10)
                ),
                Expanded(
                    flex: 1,
                    child: ListView.separated(
                        itemBuilder: (BuildContext context, int index) {
                          IMConversationInfo info =
                              controller.state.conversationList[index];
                          return conversationItemView(context, info);
                        },
                        separatorBuilder: (context, index) {
                          return const Divider(
                            height: 10,
                            color: Colors.transparent,
                          );
                        },
                        itemCount: controller.state.conversationList.length))
              ],
            ))));
  }

  ///
  /// 系统消息
  ///
  Widget lastInstantMsgItemView(BuildContext context) {
    InstantMsg? msg = controller.instantMsg;
    String lastTime = '';
    String subTitle = '';
    if (msg?.createTime != null) {
      DateTime? time = DateTime.tryParse(msg?.createTime ?? "");
      if (time != null) {
        lastTime = time.friendlyTime();
      }
      subTitle = msg?.title ?? '';
    }
    return Container(
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(10)),
          color: Theme.of(context).colorScheme.background,
        ),
        child: ListTile(
          leading: const SizedBox(
            width: 50,
            height: 50,
            child: AssetsImageView("icon_msg.png"),
          ),
          title: Text(
            'im_instant_msg_title'.tr,
            softWrap: true,
            textAlign: TextAlign.left,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
            style: Theme.of(context).textTheme.bodyLarge,
          ),
          subtitle: Text(
            subTitle,
            softWrap: true,
            textAlign: TextAlign.left,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
            style: Theme.of(context).textTheme.bodyMedium,
          ),
          trailing:
              Text(lastTime, style: Theme.of(context).textTheme.bodySmall),
          onTap: () => controller.clickInstant(),
        ));
  }

  Widget conversationItemView(BuildContext context, IMConversationInfo info) {
    String lastTime = '';
    String subTitle = '';
    if (info.lastMessage != null) {
      var last = info.lastMessage!;
      DateTime? time = DateTime.tryParse(last.createTime ?? "");
      if (time != null) {
        lastTime = time.friendlyTime();
      }
      subTitle = last.toBody()?.conversationBodyString() ?? '';
    }
    return Container(
        decoration: BoxDecoration(
          borderRadius: const BorderRadius.all(Radius.circular(10)),
          color: Theme.of(context).colorScheme.background,
        ),
        child: ListTile(
          leading: O2UI.badgeView((info.unreadNumber ?? 0), conversationAvatar(info)),
          title: Text(
            conversationName(info),
            softWrap: true,
            textAlign: TextAlign.left,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
            style: Theme.of(context).textTheme.bodyLarge,
          ),
          subtitle: Text(
            subTitle,
            softWrap: true,
            textAlign: TextAlign.left,
            overflow: TextOverflow.ellipsis,
            maxLines: 1,
            style: Theme.of(context).textTheme.bodyMedium,
          ),
          trailing:
              Text(lastTime, style: Theme.of(context).textTheme.bodySmall),
          onTap: () => controller.tapOpenConversation(info),
        ));
  }

  ///
  /// 头像
  /// 群聊使用多个用户头像拼接
  /// 单聊是对方头像
  ///
  Widget conversationAvatar(IMConversationInfo info) {
    if (info.type == O2.imConversationTypeGroup) {
      if (info.personList != null && info.personList!.isNotEmpty) {
        var count = info.personList?.length ?? 0;
        return SizedBox(
            width: 50,
            height: 50,
            child: NineGridView(
              width: 50,
              height: 50,
              padding: const EdgeInsets.all(5),
              space: 5,
              arcAngle: 60, // qqGp 中间间隙的角度
              type: NineGridType.qqGp, //NineGridType.weChat, NineGridType.weiBo
              itemCount: count,
              itemBuilder: (BuildContext context, int index) {
                var personDn = info.personList![index];
                return O2UI.personNetworkImage(personDn);
              },
            ));
      }
    } else {
      var personDn = info.personList?.firstWhereOrNull((element) =>
          element != O2ApiManager.instance.o2User?.distinguishedName);
      if (personDn != null) {
        return SizedBox(
            width: 50, height: 50, child: O2UI.personAvatar(personDn, 25));
      }
    }
    return const SizedBox(
        width: 50,
        height: 50,
        child: CircleAvatar(
          radius: 25,
          backgroundColor: Colors.white,
          backgroundImage: AssetImage('assets/images/group_default.png'),
        ));
  }

  /// 会话标题
  String conversationName(IMConversationInfo info) {
    // 单聊
    if (info.type == O2.imConversationTypeSingle) {
      var otherParty = info.personList?.firstWhereOrNull((element) =>
          element != O2ApiManager.instance.o2User?.distinguishedName);
      if (otherParty != null && otherParty.isNotEmpty) {
        if (otherParty.contains("@")) {
          return otherParty.o2NameCut();
        }
        return otherParty;
      }
      return "";
    } else {
      return info.title ?? "";
    }
  }
}
